from django.shortcuts import render
from django.views import View
from .models import Sensor, MonitoringData, AlertLog, Project, Announcement, Gateway
from django.db.models import Count
from django.contrib.sessions.models import Session

class DashboardView(View):
    def get(self, request):
        sensors = Sensor.objects.all()
        status_counts = sensors.values('status').annotate(count=Count('status'))
        alerts = AlertLog.objects.filter(is_resolved=False).order_by('-timestamp')[:5]
        projects = Project.objects.all()
        
        context = {
            'sensors': sensors,
            'status_counts': {item['status']: item['count'] for item in status_counts},
            'alerts': alerts,
            'projects': projects
        }
        return render(request, 'dashboard.html', context)

class DataVisualizationView(View):
    def get(self, request, parameter):
        sensors = Sensor.objects.all()
        parameter_map = {
            'stress': '应力',
            'displacement': '位移',
            'seepage': '渗流',
            'temperature': '温度'
        }
        
        context = {
            'title': f'{parameter_map[parameter]}数据可视化',
            'parameter_name': parameter_map[parameter],
            'parameter_unit': self.get_parameter_unit(parameter),
            'sensors': sensors
        }
        return render(request, 'data_visualization.html', context)
    
    def get_parameter_unit(self, parameter):
        units = {
            'stress': 'kPa',
            'displacement': 'mm',
            'seepage': 'L/s',
            'temperature': '°C'
        }
        return units.get(parameter, '')

class DeviceManagementView(View):
    def get(self, request):
        sensors = Sensor.objects.all()
        status_counts = sensors.values('status').annotate(count=Count('status'))
        maintenance_list = sensors.filter(last_maintenance__isnull=False).order_by('last_maintenance')[:5]
        
        context = {
            'status_counts': {item['status']: item['count'] for item in status_counts},
            'maintenance_list': maintenance_list,
            'sensor_list': sensors[:10]
        }
        return render(request, 'device_management.html', context)

class IndexView(View):
    def get(self, request):
        announcements = Announcement.objects.order_by('-created_at')[:5]
        active_sessions = Session.objects.filter(expire_date__gte=timezone.now())
        gateways = Gateway.objects.all()
        
        context = {
            'announcements': announcements,
            'online_users': active_sessions.count(),
            'gateways': gateways
        }
        return render(request, 'index.html', context)